<template>
  <div class="tablePaganations">
    <a-config-provider>
      <a-table
        class="ant-table-striped"
        bordered
        size="small"
        height="1000px"
        :columns="columns"
        :loading="isLoading"
        :scroll="{ y: yScroll }"
        :data-source="dataSource"
        :row-key="(record) => record.id"
        :pagination="havePage ? pagination : false"
        @change="tableChange"
        @resize-column="handleResizeColumn"
        :row-selection="
          isSelect
            ? {
                selectedRowKeys: state.selectedRowKeys,
                onSelect: selectEvent,
                onSelectAll: selectAllEvent,
              }
            : null"
        :row-class-name="
          (_record, index) => (index % 2 === 1 ? 'table-striped' : null)
        "
      >
        <template
          v-for="(item, index) in renderArr"
          #[item]="scope"
          :key="index"
        >
          <slot :name="item" :scope="scope" v-bind="scope || {}" />
        </template>
      </a-table>
    </a-config-provider>
  </div>
</template>
  
<script setup>
import {
  useSlots,
  ref,
  reactive,
  defineProps,
  defineEmits,
  watch,
  defineExpose,
} from "vue";
// import zhCN from "ant-design-vue/lib/locale-provider/zh_CN";
// const locale = ref(zhCN);
const props = defineProps({
  // 表头数据
  columns: {
    type: Object,
    required: true,
  },
  // 表格数据
  dataSource: {
    type: Object,
    required: true,
  },
  // 是否可选
  isSelect: {
    type: Boolean,
    default: false,
  },
  // loading
  isLoading: {
    type: Boolean,
  },
  // 总数
  total: {
    type: Number,
    default: 0,
  },
  // 纵向滚动值
  yScroll: {
    type: Number,
    default: 530,
  },
  // 是否有分页
  havePage: {
    type: Boolean,
    default: true,
  },
});
// 最后一次的排序标记
const lastSorter = reactive({ field: "", order: "" });
//  选择数据
const state = reactive({
  selectedRows: [],
  selectedRowKeys: [],
});

// 分页配置
const pagination = reactive({
  showQuickJumper: true,
  current: 1,
  pageSize: 20, // 默认每页显示数量
  showSizeChanger: true, // 显示可改变每页数量
  pageSizeOptions: ["20", "50", "100", "200", "300", "500"], // 每页数量选项值
  showTotal: (total, range) =>
    range[0] + "-" + range[1] + "条" + " 共" + total + "条", // 显示总数
  onShowSizeChange: (current, pageSize) => showSizeChange(current, pageSize),
  onChange: (current, pageSize) => changePage(current, pageSize), //点击页码事件
  total: props.total,
});
const emit = defineEmits(["getPageParams", "getSelectColumn", "getTableSort"]);

// 可伸缩列
const handleResizeColumn = (w, col) => {
  col.width = w;
};

//点击页码事件
const changePage = (current, size) => {
  pagination.current = current;
  emit("getPageParams", pagination.current, size);
};

// 改变每页数量时更新显示
const showSizeChange = (current, pageSize) => {
  setTimeout(() => {
    pagination.current = 1;
    emit("getPageParams", pagination.current, pageSize);
  });
  pagination.pageSize = pageSize;
};

// 选择每一项操作
const selectEvent = (record, selected, selectedRows) => {
  state.selectedRows = selectedRows.map((pro) => pro);
  state.selectedRowKeys = selectedRows.map((pro) => pro.id);
  emit("getSelectColumn", state);
};

// 全选按钮操作
const selectAllEvent = (selected, selectedRows, changeRows) => {
  // 实现一：点击以后全选所有分页数据
  if (selected) {
    // 全选
    state.selectedRows = props.dataSource.map((item) => item);
    state.selectedRowKeys = props.dataSource.map((item) => item.id);
  } else {
    // 反选
    state.selectedRows = [];
    state.selectedRowKeys = [];
  }
  // 实现二：点击以后只选择当前分页数据
  // if (selected) {
  //   state.selectedRows = selectedRows;
  //   changeRows.forEach((item) => {
  //     state.selectedRowKeys.push(item.id);
  //   });
  // } else {
  //   changeRows.forEach((item) => {
  //     let index = state.selectedRowKeys.indexOf(item.id);
  //     if (index >= 0) {
  //       state.selectedRows.splice(index, 1);
  //       state.selectedRowKeys.splice(index, 1);
  //     }
  //   });
  // }
  emit("getSelectColumn", state);
};

// 获取排序信息, pagination, filters 变化时也会触发所以对sorter进行判断限制执行
const tableChange = (pagination, filters, sorter) => {
  if (Object.keys(sorter).length > 0) {
    if (sorter.field != lastSorter.field && sorter.order != lastSorter.order) {
      lastSorter.field = sorter.field;
      lastSorter.order = sorter.order;
      emit("getTableSort", sorter);
    }
    if (sorter.field != lastSorter.field && sorter.order == lastSorter.order) {
      lastSorter.field = sorter.field;
      lastSorter.order = sorter.order;
      emit("getTableSort", sorter);
    }
    if (sorter.field == lastSorter.field && sorter.order != lastSorter.order) {
      lastSorter.field = sorter.field;
      lastSorter.order = sorter.order;
      emit("getTableSort", sorter);
    }
  }
};

// 清空选择
const clear = () => {
  state.selectedRowKeys = [];
  state.selectedRows = [];
  emit("getSelectColumn", state.selectedRows);
};

// 回到第一页
const backFirstPage = () => {
  pagination.current = 1;
  emit("getPageParams", pagination.current, pagination.pageSize);
};

// 将组件方法暴露出去
defineExpose({ clear, backFirstPage });

// 监听total变化
watch(
  props,
  (newData) => {
    pagination.total = newData.total;
  },
  { immediate: true, deep: true }
);

// 插槽的实例
const slots = useSlots();
const renderArr = Object.keys(slots);
</script>
<style scoped>
.tablePaganations {
  width: 100%;
  margin-top: 20px;
  margin-bottom: 20px;
}
.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa;
}
</style>